<template>
  <div class="card content-box">
    <div class="detail-header">
      <h2>工单详情</h2>
      <el-button @click="handleBack">返回列表</el-button>
    </div>

    <div v-loading="loading" class="detail-content">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编码">
          {{ workOrderDetail.workOrderCode }}
        </el-descriptions-item>
        <el-descriptions-item label="产品型号">
          {{ workOrderDetail.productModel }}
        </el-descriptions-item>
        <el-descriptions-item label="计划数量">
          {{ workOrderDetail.plannedQuantity }}
        </el-descriptions-item>
        <el-descriptions-item label="完成数量">
          {{ workOrderDetail.completedQuantity || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <el-tag :type="getStatusType(workOrderDetail.status)">
            {{ getStatusText(workOrderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工艺路线编码">
          {{ workOrderDetail.routeCode || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="产线编码">
          {{ workOrderDetail.productionLineCode || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ workOrderDetail.createdTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" v-if="workOrderDetail.updatedTime">
          {{ workOrderDetail.updatedTime }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 操作按钮区域 -->
      <div class="action-buttons" v-if="workOrderDetail.id">
        <el-button type="primary" @click="handleEdit">编辑工单</el-button>
        
        <!-- 根据状态显示不同操作按钮 -->
        <el-button v-if="workOrderDetail.status === 'CREATED'" type="success" @click="handleRelease">下达工单</el-button>
        <el-button v-if="workOrderDetail.status === 'RELEASED'" type="warning" @click="handleStart">开始生产</el-button>
        <el-button v-if="workOrderDetail.status === 'STARTED'" type="warning" @click="handleSuspend">暂停工单</el-button>
        <el-button v-if="workOrderDetail.status === 'SUSPENDED'" type="success" @click="handleResume">恢复生产</el-button>
        <el-button v-if="workOrderDetail.status === 'STARTED'" type="success" @click="handleComplete">完成工单</el-button>
        <el-button v-if="workOrderDetail.status === 'COMPLETED'" type="info" @click="handleClose">关闭工单</el-button>
        <el-button v-if="['CREATED', 'RELEASED'].includes(workOrderDetail.status)" type="danger" @click="handleCancel">取消工单</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="workOrderDetail">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getWorkOrderById,
  releaseWorkOrder,
  startWorkOrder,
  suspendWorkOrder,
  resumeWorkOrder,
  completeWorkOrder,
  closeWorkOrder,
  cancelWorkOrder,
  type WorkOrder
} from "@/api/modules/workorder";

const route = useRoute();
const router = useRouter();
const loading = ref(false);

// 工单详情数据
const workOrderDetail = reactive<Partial<WorkOrder.WorkOrderListItem>>({});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'CREATED': 'info',
    'RELEASED': 'warning',
    'STARTED': 'primary',
    'SUSPENDED': 'warning',
    'COMPLETED': 'success',
    'CLOSED': 'info',
    'CANCELLED': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'CREATED': '已创建',
    'RELEASED': '已下达',
    'STARTED': '生产中',
    'SUSPENDED': '已暂停',
    'COMPLETED': '已完成',
    'CLOSED': '已关闭',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 获取工单详情
const getWorkOrderDetail = async (id: string) => {
  loading.value = true;
  try {
    const res = await getWorkOrderById(id);
    Object.assign(workOrderDetail, res.data);
  } catch (error) {
    console.error('获取工单详情失败:', error);
    ElMessage.error('获取工单详情失败');
    router.push('/workorder');
  } finally {
    loading.value = false;
  }
};

// 返回列表
const handleBack = () => {
  router.push('/workorder');
};

// 编辑工单
const handleEdit = () => {
  router.push(`/workorder/form?id=${workOrderDetail.id}`);
};

// 下达工单
const handleRelease = async () => {
  try {
    await releaseWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单下达成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单下达失败:', error);
    ElMessage.error('工单下达失败');
  }
};

// 开始工单
const handleStart = async () => {
  try {
    await startWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单开始成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单开始失败:', error);
    ElMessage.error('工单开始失败');
  }
};

// 暂停工单
const handleSuspend = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入暂停原因', '暂停工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '暂停原因不能为空'
    });
    
    await suspendWorkOrder(workOrderDetail.id!, { suspendReason: reason });
    ElMessage.success('工单暂停成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单暂停失败:', error);
      ElMessage.error('工单暂停失败');
    }
  }
};

// 恢复工单
const handleResume = async () => {
  try {
    await resumeWorkOrder(workOrderDetail.id!);
    ElMessage.success('工单恢复成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    console.error('工单恢复失败:', error);
    ElMessage.error('工单恢复失败');
  }
};

// 完成工单
const handleComplete = async () => {
  try {
    const { value: quantity } = await ElMessageBox.prompt(
      `计划数量：${workOrderDetail.plannedQuantity}，请输入完成数量`, 
      '完成工单', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数量'
      }
    );
    
    await completeWorkOrder(workOrderDetail.id!, { completedQuantity: parseInt(quantity) });
    ElMessage.success('工单完成成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单完成失败:', error);
      ElMessage.error('工单完成失败');
    }
  }
};

// 关闭工单
const handleClose = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入关闭原因', '关闭工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '关闭原因不能为空'
    });
    
    await closeWorkOrder(workOrderDetail.id!, { closeReason: reason });
    ElMessage.success('工单关闭成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单关闭失败:', error);
      ElMessage.error('工单关闭失败');
    }
  }
};

// 取消工单
const handleCancel = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入取消原因', '取消工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '取消原因不能为空'
    });
    
    await cancelWorkOrder(workOrderDetail.id!, { cancelReason: reason });
    ElMessage.success('工单取消成功');
    getWorkOrderDetail(workOrderDetail.id!);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('工单取消失败:', error);
      ElMessage.error('工单取消失败');
    }
  }
};

// 页面初始化
onMounted(() => {
  const id = route.params.id as string;
  if (id) {
    getWorkOrderDetail(id);
  } else {
    ElMessage.error('工单ID不能为空');
    router.push('/workorder');
  }
});
</script>

<style scoped>
.content-box {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.detail-content {
  min-height: 400px;
}

.action-buttons {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 120px;
}
</style>